package com.xn.app.muying.adpter;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.FileCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.xn.app.muying.R;
import com.xn.app.muying.activity.FarMonitorListActivity;
import com.xn.app.muying.bean.FarMonitorListBean;

import java.io.File;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/11/25.
 */
public class FarMonitorListAdapter extends BaseAdapter {
    private final LayoutInflater inflater;
    private Context context;
    private ArrayList<FarMonitorListBean> list = new ArrayList<>();

    public FarMonitorListAdapter(Context context) {
        super();
        this.context = context;
        inflater = LayoutInflater.from(context);
    }

    public void getData(ArrayList<FarMonitorListBean> data) {
        this.list.addAll(data);
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {

        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
//        if (view == null) {
        view = inflater.inflate(R.layout.farmonitorlist_item, null);
        TextView tv_state = (TextView) view.findViewById(R.id.farmonitorlist_item_state);
        TextView tv_hospital = (TextView) view.findViewById(R.id.farmonitorlist_item_hospital);
        TextView tv_type = (TextView) view.findViewById(R.id.farmonitorlist_item_type);
        TextView tv_time = (TextView) view.findViewById(R.id.farmonitorlist_item_time);
        final TextView tv_look = (TextView) view.findViewById(R.id.farmonitorlist_item_look);
        final TextView tv_progress = (TextView) view.findViewById(R.id.farmonitorlist_item_progress);
//            view.setTag(holder);
//        } else {
//            holder = (ViewHolder) view.getTag();
//        }
        tv_state.setText(list.get(i).getRemoteMonitorReportStatusDescription());
        tv_hospital.setText(list.get(i).getCompanyName());
        tv_type.setText(list.get(i).getServiceTypeDescription());
        if (list.get(i).getReportGenerateTime().equals("null")) {
            tv_time.setText("");
        } else {
            String[] strs = list.get(i).getReportGenerateTime().split("T");
            String[] strs2 = strs[1].split(":");
            tv_time.setText(strs[0] + " " + strs2[0] + ":" + strs2[1]);
        }

        tv_look.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!FarMonitorListActivity.isDownload) {
                    if (!list.get(i).getReportUrl().equals("null")) {
                        if (list.get(i).getReportUrl().matches("[a-zA-z]+://[^\\s]*")) {
                            FarMonitorListActivity.isDownload = true;
                            String url = list.get(i).getReportUrl();
                            OkHttpUtils.get(url).tag(this)
                                    .execute(new DownloadFileCallBack(Environment.getExternalStorageDirectory() +
                                            "/temp", "qcl.pdf", tv_look, tv_progress,context));//保存到sd卡
                        } else {
                            Toast.makeText(context, "打开文件失败", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        FarMonitorListActivity.isDownload = false;
                        Toast.makeText(context, "报告暂未生产", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(context, "正在加载其他的报告", Toast.LENGTH_SHORT).show();
                }

            }
        });
        return view;

    }

    class ViewHolder {
        TextView tv_state, tv_hospital, tv_type, tv_time, tv_look, tv_progress;
    }


    private class DownloadFileCallBack extends FileCallback {
        private TextView tv_look, tv_progress;
        private Context context;

        public DownloadFileCallBack(String destFileDir, String destFileName, TextView tv_look, TextView tv_progress, Context context) {
            super(destFileDir, destFileName);
            this.tv_look = tv_look;
            this.tv_progress = tv_progress;
            this.context=context;
        }

        @Override
        public void onBefore(BaseRequest request) {
        }

        @Override
        public void onResponse(boolean isFromCache, File file, Request request, Response response) {
            tv_look.setClickable(true);
            tv_progress.setVisibility(View.GONE);
//            Intent intent = new Intent();
//            intent.setClass(context, PdfActivity.class);
//            context.startActivity(intent);
            /**暂行解决方案*/
            Intent intent = getPdfFileIntent(file.toString());
            context.startActivity(intent);
            FarMonitorListActivity.isDownload = false;

        }

        @Override
        public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
            tv_look.setClickable(false);
            tv_progress.setVisibility(View.VISIBLE);
            tv_progress.setText((Math.round(progress * 10000) * 1.0f / 100) + "%");
        }

        @Override
        public void onError(boolean isFromCache, Call call, @Nullable Response response, @Nullable Exception e) {
            super.onError(isFromCache, call, response, e);
            FarMonitorListActivity.isDownload = false;
        }
    }

    /**
     * android获取一个用于打开PDF文件的intent
     * @param path 要打开的文件的绝对路径
     * @return
     */
    public Intent getPdfFileIntent( String path )

    {

        Intent intent = new Intent(Intent.ACTION_VIEW);//Intent.ACTION_VIEW = "android.intent.action.VIEW"

        intent.addCategory(Intent.CATEGORY_DEFAULT);//Intent.CATEGORY_DEFAULT = "android.intent.category.DEFAULT"

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        Uri uri = Uri.fromFile(new File(path ));

        intent.setDataAndType(uri, "application/pdf");

        return intent;

    }
}
